// require jquery.

$(function() {
    function showMessage(title, body) {
      $("#alert-info").html(title);
      $("#alert .modal-body").html(body);
      $('#alert').modal('show');
    }
    function editBtnClick(event) {
      event.preventDefault();
      $this = $(this);
      $task = $this.closest('.inner');
      toggleEditTask($task);
    }
    function submitTask($task) {
      var url = $('.edit-btn', $task).attr('href');
      var tokens = url.split(/[\=\?]/);
      var $progress = $('.progress input');
      var progress_val = $progress.val()
      $progress.closest(".bar").css("width", progress_val + "%")
      var params = {
        title: $('h2 input', $task).val(),
        description: $('.description textarea', $task).val(),
        progress: progress_val,
        task_id: tokens[2]
      };
      $.ajax({
        url: tokens[0],
        data: params,
        type: 'post'
      }).done(function(data) {
        toggleEditTask($task);
        showMessage('Done!', 'You have successfully submit the changes.');
      }).error(function(data) {
            console.log(data);
      });
    }
    function toggleEditTask($task) {
      if (! $task.data('edit')) {
        $task.data('edit', true);
        $.data($task, 'edit', true);

        $('.edit-btn', $task).off().on('click', function(event) {
          event.preventDefault();
          submitTask($task);
        }).children('i').attr('class', 'icon-ok-circle');
        $('.del-btn', $task).on('click', function(event) {
          event.preventDefault();
          toggleEditTask($task);
        }).children('i').attr('class', 'icon-ban-circle');

      } else {
        $task.removeData('edit');
        $('.edit-btn', $task).off().on('click', editBtnClick).children('i').attr('class', 'icon-edit');
        $('.del-btn', $task).off().children('i').attr('class', 'icon-remove');

      }
      $('[data-editor]', $task).editor('toggle');
    }
    $(".edit-btn").on('click', editBtnClick);

    $(".sidebar a.title").on('click', function(event) {
      event.preventDefault();
      var $this = $(this);
      $this.siblings().slideToggle();
    });
  });
